const { exec } = require("child_process");
const p = require("path");
const fs = require("fs-extra");

function exec_sync(cmd) {
  return new Promise((resolve, reject) => [
    exec(cmd, function (err, stdout, stderr) {
      if (err) {
        reject(new Error(err));
      } else if (stderr) {
        reject(new Error(err));
      } else {
        resolve(stdout);
      }
    }),
  ]);
}

module.exports = app => {
  class FileController extends app.Controller {
    async ping() {
      const message = this.ctx.args[0];
      await this.ctx.socket.emit(
        "res",
        `Hi! I've got your message: ping function`
      );
    }
    async file_select() {
      const message = this.ctx.args[0];
      await this.ctx.socket.emit(
        "res",
        `server >> Hi! I've got your message: ${message}`
      );
      let { type } = message;
      const { app, socket } = this.ctx;
      const id = socket.id;

      //连接命名空间
      const nsp = app.io.of("/");
      let select_plugin_path = p.join(app.baseDir, "plugins/file_select.exe");
      let cmd = `${select_plugin_path} -f ${type}`;
      let path_ret = await exec_sync(cmd);
      path_ret = JSON.parse(path_ret.trim());
      let body = {
        code: 400,
        msg: "取消选择或者选择失败，请稍后重试",
      };
      if (path_ret.code == 400) {
        nsp.sockets[id].emit(type, body);
        return;
      }
      let files = type == "file" ? [] : fs.readdirSync(path_ret.data);
      if (path_ret.code == 200) {
        body.files = files;
        body.path = path_ret.data;
        body.code = 200;
        body.msg = type == "file" ? "选择文件成功！" : "选择文件夹成功！";
      }
      nsp.sockets[id].emit(type, body);
    }

    async disconnect() {
      const message = this.ctx.args[0];
      console.log(message);
    }
  }

  return FileController;
};
